package com.scorpio.appuser.service.impl;

import com.scorpio.appuser.domain.UserAddressEntity;
import com.scorpio.appuser.mapper.UserAddressMapper;
import com.scorpio.appuser.service.UserAddressService;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.service.impl.BaseServiceImpl;
import com.scorpio.common.utils.StringUtils;
import com.scorpio.system.domain.SysAreaInfoEntity;
import com.scorpio.system.service.SysAreaInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserAddressServiceImpl extends BaseServiceImpl<UserAddressMapper, UserAddressEntity> implements UserAddressService {

    @Autowired
    private SysAreaInfoService areaInfoService;

    @Override
    public UserAddressEntity selectRecommendAddress(Long uid) {
        return baseDao.selectRecommendAddress(uid);
    }

    @Override
    public UserAddressEntity selectByUser(Long uid, Long id) {
        return baseDao.selectByUser(uid, id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAddressEntity addAddress(UserAddressEntity entity) {
        setAreaInfo(entity);
        if (baseDao.insert(entity) > 0) {
            return entity;
        } else {
            throw new CustomException("添加失败");
        }
    }

    private void setAreaInfo(UserAddressEntity entity) {
        SysAreaInfoEntity cityEntity = areaInfoService.selectByName(entity.getCityName());
        if (cityEntity == null) {
            throw new CustomException("当前城市暂不支持");
        }
        SysAreaInfoEntity provinceEntity = areaInfoService.selectById(cityEntity.getParentId());

        entity.setCityCode(cityEntity.getAreaCode());
        entity.setCityName(cityEntity.getAreaName());
        entity.setProvinceCode(provinceEntity.getAreaCode());
        entity.setProvinceName(provinceEntity.getAreaName());
        if (StringUtils.isEmpty(entity.getIsDefault())) {
            entity.setIsDefault("1");
        }
        if ("0".equals(entity.getIsDefault())) {
            baseDao.updateDefaultToNot(entity.getUid());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAddressEntity updateAddress(UserAddressEntity entity) {
        setAreaInfo(entity);
        if (baseDao.updateById(entity) > 0) {
            return entity;
        } else {
            throw new CustomException("添加失败");
        }
    }

    @Override
    public List<UserAddressEntity> appList(Long uid) {
        return baseDao.appList(uid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAddress(Long uid, Long id) {
        return baseDao.deleteByUser(uid, id);
    }

}
